package com.billionsfinance.hessian.common.utils;


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * @ ClassName: NetAddressUtils.java
 * @ Author: WeiHui-Z
 * @ Date: 2016/11/23 12:36
 * @ Version: v1.0.0
 */
public final class NetAddressUtils {

	public static String getRealIp() {
		String localIp = null;// 本地IP，如果没有配置外网IP则返回它
		String netIp = null;// 外网IP

		Enumeration<NetworkInterface> netInterfaces = null;
		try {
			netInterfaces = NetworkInterface.getNetworkInterfaces();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		InetAddress ip;
		boolean found = false;// 是否找到外网IP
		while (netInterfaces != null && netInterfaces.hasMoreElements() && !found) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration<InetAddress> address = ni.getInetAddresses();
			while (address.hasMoreElements()) {
				ip = address.nextElement();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && !ip.getHostAddress().contains(":")) {// 外网IP
					netIp = ip.getHostAddress();
					found = true;
					break;
				} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress()
						&& !ip.getHostAddress().contains(":")) {// 内网IP
					localIp = ip.getHostAddress();
				}
			}
		}
		if (netIp != null && !"".equals(netIp)) {
			return netIp;
		} else {
			return localIp;
		}
	}

	public static String getLocalHostName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (Exception e) {
			return "unknown";
		}
	}

}